﻿using System;
using System.Collections.Generic;
using fastJSON;
using System.IO;
using System.Text;


namespace ServerFramework.Tools
{
    /// <summary>
    /// 一种json形式的配置文件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static class JsonConfig<T> where T:new()
    {
        private static T _jsonObj;
        private static FileSystemWatcher _fileWatcher = null;

        public static void Init()
        {
            Load();
            _fileWatcher = new FileSystemWatcher("config/",".json");
            _fileWatcher.Changed += _fileWatcher_Changed;
            _fileWatcher.EnableRaisingEvents = true;
        }

        static void _fileWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            Load();
        }

        private static void Load()
        {
            if (!Directory.Exists("config/"))
            {
                Directory.CreateDirectory("config/");
            }
            try
            {
                string content = File.ReadAllText("config/" + typeof(T).Name + ".json");
                _jsonObj = JSON.ToObject<T>(content);
            }
            catch (Exception)
            {
                _jsonObj = new T();
                string content = JSON.ToJSON(_jsonObj);
                File.WriteAllText("config/" + typeof(T).Name + ".json", content,Encoding.UTF8);
            }
        }

        public static T Config { get { return _jsonObj; } }
    }
}
